from .BaseVectorSearcher import BaseVectorSearcher
from .ElasticsearchClient import ElasticsearchClient
from typing import Dict, List
from Logger import Logger
from ConfigManager import ConfigManager
from llm.SiliconFlowEmbeddingClient import SiliconFlowEmbeddingClient

logger = Logger.get_logger(__name__)

class EsSearcher(BaseVectorSearcher):
    """Class for handling Elasticsearch document searches"""
    
    def __init__(self, es_client: ElasticsearchClient = None):
        self.es_client = es_client or ElasticsearchClient()
        config = ConfigManager()
        token=config.get('embedding_key')
        model=config.get('embedding_model')
        self.embedding_client = SiliconFlowEmbeddingClient(token, model)
    
    def search_by_embedding(self, text: List[str], top_k: int = 10) -> List[Dict]:
        """
        Search documents using text input by first converting to embeddings
        Args:
            text: Input text or list of texts to search with
            top_k: Number of results to return per embedding
        Returns:
            List of matching documents
        """
        results = []
        for question in text:
            # Get embeddings for input text
            embedding = self.embedding_client.get_embeddings(question)
            if not embedding:
                logger.error(f"获取embedding失败: {question}")
                continue
            docs = self.es_client.vector_search(embedding, top_k)
            results.extend(docs)
        
        # Remove duplicates based on id field
        unique_results = {doc['id']: doc for doc in results}.values()
        results = list(unique_results)
        
        # Sort by file_path and page_number
        results.sort(key=lambda x: (x['file_path'], x['page_number']))
        
        # Extract text_content values from results
        text_contents = [doc['text_content'] for doc in results]
        
        return text_contents
